<?php

namespace App\Jobs;

use App\Models\Order;
use Carbon\Carbon;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AutoCompleteOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, SerializesModels;

    public $queue = 'order_auto_complete';

    public $tries = 3;

    public $timeout = 120;

    protected $collections = null;

    protected $key;
    protected $customer;

    protected $logContent = [];

    protected $StatusSuccessCode = 200;
    protected $ReasonSuccessPhrase = 'OK';

    protected $StateCompleted = [3,4,6];//快递单当前状态，包括0在途，1揽收，2疑难，3签收，4退签，5派件，6退回等7个状态
    const SystemRemark = [
        3 => '订单已签收',
        4 => '订单被退签',
        6 => '订单被退回',
    ];


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Collection $collections)
    {
        $this->collections = $collections;

        $this->key = env('EXPRESS_KEY');
        $this->customer = env('EXPRESS_CUSTOMER');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {

            $client = new \GuzzleHttp\Client([
                'base_uri' => 'http://poll.kuaidi100.com/poll/query.do',
                'timeout' => 2
            ]);

            if (!is_null($this->collections)) {
                $this->collections->each(function ($item) use ($client) {
                    try {
                        $response = $client->request('POST', '', [
                            'query' => $this->sign([
                                'com' => $item->express_name,      //快递公司编码
                                'num' => $item->express_order,     //快递单号
                                'phone' => '',                       //手机号
                                'from' => '',                       //出发地城市
                                'to' => '',                       //目的地城市
                                'resultv2' => '1',                      //开启行政区域解析
                                'id' => $item->id
                            ])
                        ]);

                        if ($response->getStatusCode() == 200 || $response->getReasonPhrase() == 'OK') {
                            $content = \GuzzleHttp\json_decode($response->getBody()->getContents(),true);
                            if(App::environment('local')){
                                Log::channel('express_api')->info('接口数据', [
                                    'com' => $item->express_name,      //快递公司编码
                                    'num' => $item->express_order,     //快递单号
                                    'phone' => '',                       //手机号
                                    'from' => '',                       //出发地城市
                                    'to' => '',                       //目的地城市
                                    'resultv2' => '1',                      //开启行政区域解析
                                    'id' => $item->id,
                                    'content' => $content
                                ]);
                            }

                            $last_data = $content['data'][0] ?: null;

                            $state = $content['state'] ?? 0;
                            if(in_array($state,$this->StateCompleted)){
                                $time = $last_data['ftime'] ?? null;
                                if(Carbon::parse($time)->addDays(3)->lt(Carbon::now())){//签收72小时自动完成订单
                                    DB::table('order')->where('id',$item->id)->update([
                                        'status'        => Order::STATUS_SUCCESS,
                                        'get_time'      => date('Y-m-d H:i:s'),
                                        'confirm_get_time'      => date('Y-m-d H:i:s'),
                                        'system_remark' => $last_data['context'] ?: self::SystemRemark[$state],
                                    ]);
                                    //报表队列加入
                                    $service = new \App\Services\ReportService($item->online_order,\App\Services\ReportService::RequestCodePickUp);
                                    \App\Jobs\HtReportApi::dispatch($service);
                                }
                            }
                        }

                    } catch (ConnectException $connectException) {
                        array_push($this->logContent, ['exception' => $connectException->getMessage()]);
                        Log::channel('express_api')->info('接口异常', $this->logContent);
                    }catch (\Exception $exception){
                        array_push($this->logContent,['exception' => $exception->getMessage()]);
                        Log::channel('express_api')->error('程序异常',$this->logContent);
                    }

                });

            }
        }catch (\Exception $exception){
            array_push($this->logContent,['exception' => $exception->getMessage()]);
            Log::channel('express_api')->error('程序异常',$this->logContent);
        }

    }

    protected function sign($param)
    {
        //请求参数
        $post_data = [];
        $post_data["customer"] = $this->customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"] . $this->key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($params, 0, -1);

        array_push($this->logContent,['sign'=>$sign]);

        return $post_data;
    }
}
